package com.zbf.filter;

import com.alibaba.fastjson.JSON;
import com.zbf.common.ResponseResult;
import com.zbf.common.ResultStatus;
import com.zbf.common.SysInfo;
import com.zbf.config.NoLoginPathConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/6/1  15:50
 * 描述: 校验登录
 */
@WebFilter
@Component
public class LoginFilter implements Filter {

    @Autowired
    private NoLoginPathConfig noLoginPathConfig;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = servletRequest1.getRequestURI();
        if(noLoginPathConfig.getPath().contains(requestURI)){
           //不需要经过登录校验的路径
           filterChain.doFilter(servletRequest,servletResponse);
        }else{

           Object attribute = servletRequest1.getSession().getAttribute(SysInfo.userInfo);

           if(attribute!=null){
               //说明登录过了
               filterChain.doFilter(servletRequest,servletResponse);

           }else{
               //设置响应头信息
               response.setHeader("Access-Control-Allow-Credentials","true");
               response.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
               response.setHeader("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,OPTIONS");
               response.setHeader("Access-Control-Allow-Origin","http://localhost:8888");
               //防止乱码
               response.setCharacterEncoding("GBK");
               ResponseResult responseResult = ResponseResult.getResponseResult()
                       .setCode(ResultStatus.AUTH_NO_LOGIN.getCode())
                       .setMsg(ResultStatus.AUTH_NO_LOGIN.getMsg());
               //写回错误信息
               response.getWriter().append(JSON.toJSONString(responseResult));
               return;

           }

        }


    }
}
